﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Day06
{
    class JsonHelper
    {
        //格式：{"属性":"值"，"属性":"值"}
        public static string ObjectToString(Object obj)
        {
            //思路：反射该对象所有属性，根据名称拼接字符
            StringBuilder builder = new StringBuilder();//频繁修改字符串时用StringBuilder
            builder.Append("{");
            Type type = obj.GetType();
            type.GetProperties();
            foreach (var p in type.GetProperties())
            {
                builder.AppendFormat("\"{0}\":\"{1}\",", p.Name, p.GetValue(obj));
            }
            builder.Remove(builder.Length -1 ,1);
            builder.Append("}");
            return builder.ToString();
        }
        //格式：{"属性":"值"，"属性":"值"}
        public static T StringToObject<T>(string json) where T:new()
        {
            //思路：根据泛型获取目标类型，创建对象。T t = new T();
            //根据json串中属性，为对象赋值。
            T t = new T();
            Type type = typeof(T);
            //属性:值，属性:值------去除{}"
            json = json.Replace("{","").Replace("}","").Replace("\"","");
            //属性:值，属性:值-----属性 值 属性 值
            string[] keyValue = json.Split(':', ',');
            for (int i = 0; i < keyValue.Length; i+=2)
            {
                //i属性索引 i+1值索引
                var property = type.GetProperty(keyValue[i]);
                object propertyVal = Convert.ChangeType(keyValue[i + 1], property.PropertyType);
                property.SetValue(t, propertyVal);
            
            }
            return t;

        }
    }
}
